'use client';

import { ChangeEvent, useTransition } from 'react';
import { useLanguage } from '../contexts/LanguageContext';

const languages = [
  { code: 'en', name: 'English', flag: '🇺🇸' },
  { code: 'zh', name: '中文', flag: '🇨🇳' },
  { code: 'ja', name: '日本語', flag: '🇯🇵' },
  { code: 'ko', name: '한국어', flag: '🇰🇷' },
  { code: 'fr', name: 'Français', flag: '🇫🇷' },
  { code: 'de', name: 'Deutsch', flag: '🇩🇪' }
];

export function LanguageSwitcher() {
  const { locale, setLocale, t } = useLanguage();
  const [isPending, startTransition] = useTransition();

  const onSelectChange = (event: ChangeEvent<HTMLSelectElement>) => {
    const nextLocale = event.target.value as typeof locale;
    startTransition(() => {
      setLocale(nextLocale);
    });
  };

  const currentLanguage = languages.find(lang => lang.code === locale);

  return (
    <div className="flex items-center gap-2 bg-gray-800/90 backdrop-blur-sm rounded-lg px-3 py-2 border border-gray-600 shadow-lg">
      <span className="text-sm text-gray-200">
        {t('app.language')}:
      </span>
      <div className="relative">
        <select
          value={locale}
          onChange={onSelectChange}
          disabled={isPending}
          className="appearance-none bg-gray-700 text-white border border-gray-600 rounded px-2 py-1 text-sm font-medium cursor-pointer disabled:cursor-not-allowed pr-8 outline-none focus:border-purple-500"
        >
          {languages.map((language) => (
            <option key={language.code} value={language.code} className="bg-gray-700 text-white">
              {language.flag} {language.name}
            </option>
          ))}
        </select>
        <div className="absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
      </div>
      {currentLanguage && (
        <span className="text-xs text-gray-400">
          {currentLanguage.flag}
        </span>
      )}
    </div>
  );
}
